package cn.lkx.eduservice.controller.front;

import cn.lkx.commonutils.JwtUtils;
import cn.lkx.commonutils.R;
import cn.lkx.commonutils.orderVo.OrderCourseVo;
import cn.lkx.eduservice.client.OrderClient;
import cn.lkx.eduservice.entity.EduCourse;
import cn.lkx.eduservice.entity.chapter.ChapterVo;
import cn.lkx.eduservice.entity.vo.frontvo.CourseDetailVo;
import cn.lkx.eduservice.entity.vo.frontvo.CourseQueryVo;
import cn.lkx.eduservice.service.EduChapterService;
import cn.lkx.eduservice.service.EduCourseService;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/eduservice/frontcourse")
@CrossOrigin
public class CourseFrontController {
    @Autowired
    private EduCourseService courseService;
    @Autowired
    private EduChapterService chapterService;
    @Autowired
    private OrderClient orderClient;

    //分页 条件获取课程列表信息
    @PostMapping("pageAndContition/{page}/{limit}")
    public R pageAndContition(@PathVariable Long page,
                              @PathVariable Long limit,
                              @RequestBody(required = false) CourseQueryVo courseQueryVo){
        Page<EduCourse> coursePage = new Page<>(page,limit);
        Map<String,Object> map = courseService.getCourseFrontList(coursePage,courseQueryVo);

        return R.ok().data(map);
    }
    //课程详情获取
    @GetMapping("getCourseDetail/{courseId}")  //根据请求头获得会员id
    public R getCourseDetailById(@PathVariable String courseId, HttpServletRequest request){
        //查询该课程的 课程信息和讲师信息
        CourseDetailVo courseDetailVo = courseService.getCourseDetailById(courseId);
        //获得该课程的 章节小节
        List<ChapterVo> chapterVoList = chapterService.getChapterVideoByCourseId(courseId);

        //远程调用order模块 判断登录会员是否购买该课程 (后加的：完善支付时添加的)
        String memberId = JwtUtils.getMemberIdByJwtToken(request);
        if(memberId!=""){
            boolean buyCourse = orderClient.isBuyCourse(memberId, courseId);

            return R.ok().data("chapterVoList",chapterVoList).data("courseDetailVo",courseDetailVo).data("isBuy",buyCourse);
        }else {
            return R.ok().data("chapterVoList",chapterVoList).data("courseDetailVo",courseDetailVo);
        }

    }

    // 给order模块远程调用的 根据课程id获取课程和讲师信息(课程封面、标题、讲师名称)
    @GetMapping("getCourseToOrder/{courseId}")
    public OrderCourseVo getCourseInfoToOrder(@PathVariable String courseId){
        CourseDetailVo courseDetailVo = courseService.getCourseDetailById(courseId);
        OrderCourseVo orderCourseVo = new OrderCourseVo();
        BeanUtils.copyProperties(courseDetailVo,orderCourseVo);

        return orderCourseVo;
    }
}
